package com.echoesnet.echoesshortvideo.Activities;

import android.app.Activity;
import android.arch.lifecycle.Observer;
import android.content.Intent;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.content.LocalBroadcastManager;
import android.text.Editable;
import android.text.Selection;
import android.text.TextWatcher;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.echoesnet.echoesshortvideo.Constant.CommonConstant;
import com.echoesnet.echoesshortvideo.R;
import com.echoesnet.echoesshortvideo.Utils.CommonUtils;
import com.echoesnet.echoesshortvideo.Utils.ToastUtils;
import com.echoesnet.echoesshortvideo.ViewModels.StepRegisterViewModel;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static android.content.Intent.FLAG_ACTIVITY_CLEAR_TOP;
import static android.content.Intent.FLAG_ACTIVITY_SINGLE_TOP;

public class RegisterPasswordAct extends BaseActivity
{


    @BindView(R.id.cancle)
    ImageView cancle;
    @BindView(R.id.phone)
    TextView phone;
    @BindView(R.id.password)
    EditText edPassword;
    @BindView(R.id.nextOk)
    ImageView nextOk;
    @BindView(R.id.scrollLayout)
    RelativeLayout rl;
    private String code;
    private StepRegisterViewModel lModel;
    //屏幕高度
    private int screenHeight = 0;
    //软件盘弹起后所占高度阀值
    private int keyHeight = 0;

    @BindView(R.id.root_layout)
    View activityRootView;
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_login_register_password);
        ButterKnife.bind(this);
        phone.setText("+86 "+getIntent().getStringExtra("phone"));
        code=getIntent().getStringExtra("code");
        edPassword.addTextChangedListener(new TextWatcher()
        {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after)
            {

            }
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count)
            {
                //验证手机号
                if(!CommonUtils.verifyInput(1, edPassword.getText().toString().trim()))
                {
                    nextOk.setClickable(false);
                    nextOk.setAlpha(0.5f);
                }
                else
                {
                    nextOk.setClickable(true);
                    nextOk.setAlpha(1f);
                }

                Selection.setSelection(edPassword.getText(), edPassword.getText().length());

            }
            @Override
            public void afterTextChanged(Editable s)
            {

            }
        });

        lModel=new StepRegisterViewModel();
        lModel.getLiveData().observe(this, new Observer<String>()
        {
            @Override
            public void onChanged(@Nullable String type)
            {
                if (type==null)
                    return;

                if ("registerOk".equals(type))
                {
                    Toast.makeText(RegisterPasswordAct.this, "注册成功", Toast.LENGTH_SHORT).show();
                    startActivity(new Intent(RegisterPasswordAct.this,MakeUserInfo.class));
                    Intent intent=new Intent(CommonConstant.REQUEST_LOGIN_CODE);
                    LocalBroadcastManager.getInstance(RegisterPasswordAct.this).sendBroadcast(intent);
                    finish();
                }


            }
        });

        //获取屏幕高度
        screenHeight = CommonUtils.getScreenHeight(this);
        //阀值设置为屏幕高度的1/3
        keyHeight = screenHeight/3;
        //添加layout大小发生改变监听器
        activityRootView.getViewTreeObserver().addOnGlobalLayoutListener(layoutListener);

        nextOk.setClickable(false);
        Selection.setSelection(edPassword.getText(), edPassword.getText().length());
    }


    @OnClick({R.id.cancle, R.id.layout_hint, R.id.password, R.id.nextOk})
    public void onViewClicked(View view)
    {
        switch (view.getId())
        {
            case R.id.cancle:
                Intent intent=new Intent(this,LoginStepRegisterAct.class);
                intent.putExtra("code",code);
                intent.putExtra("phone",phone.getText().toString().replace("+86","").trim());
                new Handler().postDelayed(()->{exitAnim2();},100);
                startActivity(intent);

                overridePendingTransition(R.anim.out_to_top,R.anim.out_to_bottom_abit);
                break;
            case R.id.phone_code:
                break;
            case R.id.nextOk:
                if(CommonUtils.isFastDoubleClick())
                {
                    return;
                }
                lModel.register(phone.getText().toString().replace("+86","").trim()
                        ,edPassword.getText().toString().trim());
                break;
        }

    }



    private void exitAnim2()
    {
        Animation animation = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.out_to_bottom_abit);
        animation.setDuration(350);
        animation.setFillAfter(true);
        animation.setFillBefore(false);
        animation.setAnimationListener(new Animation.AnimationListener()
        {
            @Override
            public void onAnimationStart(Animation animation)
            {

            }
            @Override
            public void onAnimationEnd(Animation animation)
            {
                finish();
            }
            @Override
            public void onAnimationRepeat(Animation animation)
            {

            }
        });
        activityRootView.startAnimation(animation);

    }

    @Override
    public void onBackPressed()
    {
        Intent intent=new Intent(this,LoginStepRegisterAct.class);
        intent.putExtra("code",code);
        intent.putExtra("phone",phone.getText().toString().replace("+86","").trim());
        new Handler().postDelayed(()->{exitAnim2();},100);
        startActivity(intent);

        overridePendingTransition(R.anim.out_to_top,R.anim.out_to_bottom_abit);
    }

    private void updateViewHeight(boolean flag)
    {
        RelativeLayout.LayoutParams pa= (RelativeLayout.LayoutParams) rl.getLayoutParams();
        pa.topMargin=flag?LoginAct.TOP_MARGIN:0;
        rl.setLayoutParams(pa);
    }

    ViewTreeObserver.OnGlobalLayoutListener layoutListener = new ViewTreeObserver.OnGlobalLayoutListener()
    {

        @Override
        public void onGlobalLayout()
        {
            activityRootView.getViewTreeObserver().removeOnGlobalLayoutListener(layoutListener);

            Rect r = new Rect();
            activityRootView.getWindowVisibleDisplayFrame(r);

            //现在认为只要控件将Activity向上推的高度超过了1/3屏幕高，就认为软键盘弹起
            if (screenHeight-r.bottom  > keyHeight)
            {
                updateViewHeight(true);
            } else
            {
                updateViewHeight(false);
            }
            activityRootView.getViewTreeObserver().addOnGlobalLayoutListener(layoutListener);
        }
    };
}
